package com.cc.moxingvoice.lock;

import android.app.Dialog;
import android.content.Context;
import android.databinding.ViewDataBinding;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;

import com.cc.moxingvoice.BR;
import com.cc.moxingvoice.R;
import com.cc.moxingvoice.base.BaseActivity;
import com.cc.moxingvoice.base.BaseLock;
import com.cc.moxingvoice.constant.Connection;
import com.cc.moxingvoice.constant.LocalPath;
import com.cc.moxingvoice.constant.MyUrl;
import com.cc.moxingvoice.databinding.FragmentFindBinding;
import com.cc.moxingvoice.model.FindItem;
import com.cc.moxingvoice.response.VoiceListResponse;
import com.cc.moxingvoice.ui.main.FindAdapter;
import com.cc.moxingvoice.ui.main.MainActivity;
import com.cc.moxingvoice.ui.window.MyWindowManager;
import com.cc.moxingvoice.utils.FilesUtil;
import com.cc.moxingvoice.utils.ZipUtil;
import com.cc.moxingvoice.utils.download.DownloadListner;
import com.cc.moxingvoice.utils.download.DownloadManager;
import com.cc.moxingvoice.widget.dialog.ButtonTwoDialog;
import com.cc.moxingvoice.widget.dialog.LoadDialog;
import com.superc.cframework.base.ui.CBaseRecyclerViewAdapter;

import net.lingala.zip4j.exception.ZipException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 创建日期：2018/3/24 on 17:29
 * 描述：
 * 作者：郭士超
 * QQ：1169380200
 */

public class FindLock extends BaseLock<FragmentFindBinding> {

    private List<FindItem> mList;
    private FindAdapter mAdapter;

    public FindLock(Context context, FragmentFindBinding binding) {
        super(context, binding);
    }

    public FindLock(Context context, FragmentFindBinding binding, Bundle bundle) {
        super(context, binding, bundle);
    }

    @Override
    protected void init() {
        initList();
        getVoiceList();
    }

    private void initList() {
        mList = new ArrayList<FindItem>();
        LinearLayoutManager ms = new LinearLayoutManager(mContext);
        mBinding.rvVoicePackage.setLayoutManager(ms);
        mAdapter = new FindAdapter(mContext, mList, R.layout.item_find, BR.item);
        mBinding.rvVoicePackage.setAdapter(mAdapter); // 这里或者在xml里设置adapter
        mAdapter.setOnItemClickListener(new CBaseRecyclerViewAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(ViewDataBinding binding, int position) {
                if (DownloadManager.getInstance().isDownloading(mList.get(position).getUrl())) {
                    showToast("这个我已经在下了，您歇会吧");
                    return;
                }
                showDownloadDialog(mList.get(position), position);
            }
        });
    }

    public CBaseRecyclerViewAdapter getAdapter() {
        return mAdapter;
    }

    private void showDownloadDialog(final FindItem item, final int position) {
        new ButtonTwoDialog(mContext, R.style.dialog, "你确定下载昂，如果原来有同名的就合并到一起了。", new ButtonTwoDialog.OnCloseListener() {
            @Override
            public void onClick(Dialog dialog, boolean confirm) {
                if (confirm) {
                    downloadPackage(item, position);
                    dialog.dismiss();
                }
            }
        }).setTitle(getContext().getString(R.string.hint)).show();
    }

    private void downloadPackage(final FindItem item, final int position) {
        showToast("我开始下了，你可以先去干会别的。");
        item.setState("开始下载");
        item.notifyChange();
        FilesUtil.mkdirPath(LocalPath.DOWNLOAD_PATH);

        DownloadManager.getInstance().add(item.getUrl(), LocalPath.DOWNLOAD_PATH, item.getZipName(), new DownloadListner() {

            @Override
            public void onSuccess() {
                uiShowToast(item.getTitle() + "下载好了，正在解压");
                item.setState("正在解压");
                item.notifyChange();
                try {
                    String toPath = LocalPath.VOICE_PATH;
                    FilesUtil.mkdirPath(toPath);
                    ZipUtil.Unzip4j(LocalPath.DOWNLOAD_PATH + item.getZipName(),
                            toPath, "");
                    uiShowToast(item.getTitle() + "解压也好了，你用吧");
                    item.setState("解压完成");
                    item.notifyChange();
                    ((BaseActivity) getContext()).runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ((MainActivity) getContext()).voicePackageRefreshList();
                            MyWindowManager.removeVoiceWindow(getContext());
                        }
                    });
                } catch (ZipException e) {
                    uiShowToast(item.getTitle() + "解压失败了。");
                    item.setState("解压失败");
                    item.notifyChange();
                    e.printStackTrace();
                }
            }

            @Override
            public void onProgress(float v) {
                item.setState("已下载：" + (float) (Math.round(v * 10000)) / 100 + "%");
                item.notifyChange();
            }

            @Override
            public void onPause() {

            }

            @Override
            public void onCancel() {

            }

            @Override
            public void onFailed() {
                item.setState("下载失败");
                item.notifyChange();
                uiShowToast(item.getTitle() + "下载失败了，重起程序再试一下吧。");
            }
        });

        DownloadManager.getInstance().download(item.getUrl());

    }

    private void uiShowToast(final String msg) {
        ((BaseActivity) getContext()).runOnUiThread(new Runnable() {
            @Override
            public void run() {
                showToast(msg);
            }
        });
    }

    private void getVoiceList() {
        LoadDialog.show(getContext(), "正在加载网络资源");
        // 访问网络的方法
        HashMap hashMap = new HashMap();
        Connection.getInstance().post(VoiceListResponse.class, MyUrl.GET_VOICE, hashMap, new Connection.ResponseListener() {
            @Override
            public void tryReturn(int id, Object response) {
                final VoiceListResponse result = (VoiceListResponse) response;
                LoadDialog.dismiss(getContext());
                switch (id) {
                    case 200:
                        Drawable drawable = getContext().getResources().getDrawable(R.drawable.icon);
                        int itemId = 0;
                        for (VoiceListResponse.DataBean.ListBean item : result.getData().getList()) {
                            itemId++;
                            String state;
                            if (FilesUtil.isFileExists(LocalPath.VOICE_PATH + item.getName())) {
                                state = "已下载";
                            } else {
                                state = "未下载";
                            }
                            mList.add(new FindItem(
                                    itemId + "", drawable, item.getName(), item.getPath(),
                                    result.getData().getDir_url() + "/" + item.getPath(),
                                    state));
                        }
                        mAdapter.notifyDataSetChanged();
                        break;
                    case -2:
                        showToast("你网是不是有问题啊，快去看看。");
                        break;
                    default:

                        break;
                }
            }
        });
    }

}
